/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.task.zkex.simple;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.vfs.WriteRequestMessage;
import cn.easyplatform.messages.vos.VfsVo;
import cn.easyplatform.spi.service.VfsService;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.web.ext.ComponentBuilder;
import cn.easyplatform.web.ext.Writable;
import cn.easyplatform.web.service.ServiceLocator;
import cn.easyplatform.web.task.zkex.ListSupport;
import cn.easyplatform.web.task.OperableHandler;
import cn.easyplatform.web.utils.PageUtils;
import cn.easyplatform.web.utils.WebUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.zkoss.zk.ui.Component;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @Author: <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @Description:
 * @Since: 2.0.0 <br/>
 * @Date: Created in 2019/8/21 16:31
 * @Modified By:
 */
public class CommonFileBuilder implements ComponentBuilder, Writable {

    private OperableHandler main;

    private Component ab;

    private ListSupport support;

    public CommonFileBuilder(OperableHandler main, Component ab) {
        this.main = main;
        this.ab = ab;
    }

    public CommonFileBuilder(ListSupport support, Component ab) {
        this.ab = ab;
        this.main = support.getMainHandler();
        this.support = support;
    }

    @Override
    public Component build() {
        ab.setAttribute("$proxy", this);
        PageUtils.processEventHandler(main, ab, null);
        return ab;
    }

    @Override
    public String write(String fileName, byte[] data) {
        String baseDir = getFilePath();
        try {
            boolean isLocal = !baseDir.startsWith("$707") && !baseDir.startsWith("$729");
            if (isLocal)
                baseDir = WebUtils.getFile(baseDir);
            if (isLocal) {
                String file = FilenameUtils.normalize(baseDir + "/" + fileName);
                FileUtils.writeByteArrayToFile(new File(file), data);
            } else {
                VfsVo fv = new VfsVo();
                fv.setPath(getFilePath() + "/" + fileName);
                fv.setName(fileName);
                fv.setFolder(false);
                fv.setData(data);
                IResponseMessage<?> resp = ServiceLocator.lookup(VfsService.class).write(new WriteRequestMessage(main.getId(), fv));
                if (!resp.isSuccess())
                    throw new RuntimeException(resp.getCode() + ":" + resp.getBody());
            }
            return "/servlets/download?id=" + getFilePath() + "/" + URLEncoder.encode(fileName, "utf8");
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public String getFilePath() {
        return ((Writable) ab).getFilePath();
    }
}
